// pages/personal/purchase/orderDetail/transferStorage/transferStorage.js
import { create, query } from '../../../../../utils/service.js'

const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    message:'',   // 留言
    list: [],
    getMaterialList: [],
    steelList:[],
    payInfoList:[],
    totalPrice:0,
    id:'',
    open:false,
    applyListlose:[],
    orderDetail: [],
    Sorting_point: [],
    sort_point:'',//仓库信息
    expense_info:{},
    AuxiliaryArr:[],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onlook:function(e){
    wx.navigateTo({
      url:"../orderView/orderView?id="+this.options.id
    })
  },
  bindButtonTap: function (e) {
    this.setData({
      message: e.detail.value
    })
  },
  onLoad: function (options) {
    app.globalData.payInfoList = []
    const that = this
    const id = options.id
    console.log(options.apply_materiel_data)

    query({
      url: 'api/waste/purchase/read',
      params: { id },
      back: function (data) {
        let list = data.result.pick_cargo_data.cargo_info
        app.globalData.cargo_list = list
        let applyList = data.result.apply_materiel_data.apply_materiel_info
        console.log(applyList)
        console.log(data)
        let expense_info = data.result.pick_cargo_data.expense_info
       // let steelList = data.result.apply_materiel_data.apply_materiel_info
        //console.log(steelList)
        app.globalData.transferStorageList = list
        that.setData({
          list: list,
          expense_info: expense_info,
          applyList: applyList
         // steelList: steelList
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {


  },
  onOpen: function () {
    const that = this
    that.setData({
      open: true
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    const that = this
    const id = this.options.id
    const transferStorageList = app.globalData.transferStorageList
    const payInfoList = app.globalData.payInfoList
    

    // let payInfoList = this.data.payInfoList
    let totalPrice = 0
    payInfoList.length > 0 && payInfoList.map(item => {
      const money = item.price 
      const newNumber = parseFloat(totalPrice * 1 + money * 1)
      totalPrice = newNumber.toFixed(2)
    })
    console.log(totalPrice)


    that.setData({ 
      payInfoList:payInfoList,
      totalPrice: totalPrice
     
    })
    console.log(payInfoList)
    if (transferStorageList){
      if (transferStorageList.length > 0) {
        that.setData({
          list: transferStorageList,

        })
      }
    }
    console.log(transferStorageList)
    //获取存储的分拣点信息/id
    const getAppInfo = app.globalData.sorting_info;
    const sorting_info_none = "请选择分拣点"
    console.log(getAppInfo)  
    if(getAppInfo === ""){
      this.setData({
        sorting_info: sorting_info_none
      })
    } else{
      this.setData({
        sorting_info : getAppInfo
      })
    }
    //获取已储存的分拣点最终id
    const sort_point = app.globalData.sort_id
    this.setData({
      sort_point: sort_point
    })
   // console.log(sort_point)


    //获取选项
    query({
      url: 'api/ajax/sys_config',
      params: {},
      back: function (data) {
        const pickList = data.result
        app.globalData.pickList = pickList
      }
    })
    //获取仓库和分拣点信息
    query({
      url:'api/ajax/warehouse_tree',
      params:{ id },
      back:function(data){
        const Sorting_point = data.result 
        that.setData({
          Sorting_point: Sorting_point
        })
      }
    })
   //获取辅材信息
    const Auxiliary = app.globalData.Auxiliary
    let steelList = that.data.steelList
    console.log(steelList)
    let AuxiliaryArr = that.data.AuxiliaryArr
    // AuxiliaryArr.map(item => {
    //    auxitem = item
    // })
    // console.log(auxitem)
    
    if (Auxiliary) {
      AuxiliaryArr.push(Auxiliary)

      console.log(1)
    } else {
      console.log(2)
    }

    console.log(Auxiliary)
    console.log(AuxiliaryArr)
    if (steelList){
      for (let i=0;i<steelList.length;i++){
        if (steelList[i].type  == Auxiliary.typeInfo ){
          steelList[i].storage_amount = Auxiliary.numberInfo
          steelList[i].storage_materiel_number = Auxiliary.codeInfo
        }
      }
    }
      console.log(steelList)
      app.globalData.steelList = steelList

    that.setData({
      AuxiliaryArr: AuxiliaryArr,
      steelList:steelList
    })

    //清空 缓存
    app.globalData.Auxiliary = ''
    const getMaterialList = app.globalData.getMaterialList
    //console.log(getMaterialList)
    that.setData({
      getMaterialList: getMaterialList
    })

    const orderDetail = app.globalData.orderDetail
    that.setData({
      orderDetail: orderDetail
    })
    console.log(orderDetail)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  onAdd:function(e){
    //console.log(e)
    const id = e.currentTarget.dataset.id
    app.globalData.Auxiliary = ''
    wx.navigateTo({
      url: '../materialInfo/materialInfo?id=' + id,
    })
  },
  onScan: function () {
    // 允许从相机和相册扫码
    wx.scanCode({
      success: (res) => {
        console.log(res)
        const status = res.errMsg
        if (status == 'scanCode:ok') {
          const result = res.result
          wx.navigateTo({
            url: '../materialInfo/materialInfo?result=' + result,
          })
        }
      },
      fail: (res) => {
        console.log(res)
      }
    })
  },
  //手指触摸动作开始 记录起点X坐标 --------删除货品
  touchstart: function (e) {
    //开始触摸时 重置所有删除
    this.data.AuxiliaryArr.forEach(function (v, i) {
      if (v.isTouchMove)//只操作为true的
        v.isTouchMove = false;
    })
    this.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY,
      AuxiliaryArr: this.data.AuxiliaryArr
    })
  },
  //滑动事件处理
  touchmove: function (e) {
    var that = this,
      index = e.currentTarget.dataset.index,//当前索引
      startX = that.data.startX,//开始X坐标
      startY = that.data.startY,//开始Y坐标
      touchMoveX = e.changedTouches[0].clientX,//滑动变化坐标
      touchMoveY = e.changedTouches[0].clientY,//滑动变化坐标
      //获取滑动角度
      angle = that.angle({ X: startX, Y: startY }, { X: touchMoveX, Y: touchMoveY });
    that.data.AuxiliaryArr.forEach(function (v, i) {
      v.isTouchMove = false
      //滑动超过30度角 return
      if (Math.abs(angle) > 30) return;
      if (i == index) {
        if (touchMoveX > startX) //右滑
          v.isTouchMove = false
        else //左滑
          v.isTouchMove = true
      }
    })
    //更新数据
    that.setData({
      AuxiliaryArr: that.data.AuxiliaryArr
    })
  },
  /**
   * 计算滑动角度
   * @param {Object} start 起点坐标
   * @param {Object} end 终点坐标
   */
  angle: function (start, end) {
    var _X = end.X - start.X,
      _Y = end.Y - start.Y
    //返回角度 /Math.atan()返回数字的反正切值
    return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
  },
  //删除事件
  del: function (e) {
    this.data.AuxiliaryArr.splice(e.currentTarget.dataset.index, 1)
  
    app.globalData.AuxiliaryArr = this.data.AuxiliaryArr
    
    this.setData({
      AuxiliaryArr: this.data.AuxiliaryArr
    })
  },
  //手指触摸动作开始 记录起点X坐标 --------删除货品
  touchstartPay: function (e) {
    //开始触摸时 重置所有删除
    this.data.payInfoList.forEach(function (v, i) {
      if (v.isTouchMove)//只操作为true的
        v.isTouchMove = false;
    })
    this.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY,
      payInfoList: this.data.payInfoList
    })
  },
  //滑动事件处理
  touchmovePay: function (e) {
    var that = this,
      index = e.currentTarget.dataset.index,//当前索引
      startX = that.data.startX,//开始X坐标
      startY = that.data.startY,//开始Y坐标
      touchMoveX = e.changedTouches[0].clientX,//滑动变化坐标
      touchMoveY = e.changedTouches[0].clientY,//滑动变化坐标
      //获取滑动角度
      angle = that.angle({ X: startX, Y: startY }, { X: touchMoveX, Y: touchMoveY });
    that.data.payInfoList.forEach(function (v, i) {
      v.isTouchMove = false
      //滑动超过30度角 return
      if (Math.abs(angle) > 30) return;
      if (i == index) {
        if (touchMoveX > startX) //右滑
          v.isTouchMove = false
        else //左滑
          v.isTouchMove = true
      }
    })
    //更新数据
    that.setData({
      payInfoList: that.data.payInfoList
    })
  },
  /**
   * 计算滑动角度
   * @param {Object} start 起点坐标
   * @param {Object} end 终点坐标
   */
  angle: function (start, end) {
    var _X = end.X - start.X,
      _Y = end.Y - start.Y
    //返回角度 /Math.atan()返回数字的反正切值
    return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
  },
  //删除事件
  delPay: function (e) {
    console.log(e)
    let delet = this.data.payInfoList.splice(e.currentTarget.dataset.index, 1)
    // console.log(delet)
    let totalPrice = this.data.totalPrice
    let payInfoList = this.data.payInfoList
    let money = []
    for(let i=0;i<payInfoList.length;i++){
      money.push(payInfoList[i].price)
      //money = payInfoList[i].price
    }
    let newNumber = 0
    for(let j=0;j<money.length;j++){
      newNumber += Number(money[j]) 
    }
    totalPrice = newNumber.toFixed(2)
    this.setData({
      payInfoList: this.data.payInfoList,
      totalPrice: totalPrice
    })
    app.globalData.payInfoList = this.data.payInfoList
  },
  bindNumber: function (e) {
    const that = this
    const applyList = that.data.applyList
    const id = e.currentTarget.dataset.id
    console.log(id)
    const numberValue = e.detail.value
    for (let i = 0; i < applyList.length; i++){
      if(id == applyList[i].id){
        applyList[i].storage_amount = Number(numberValue)
      }
    }
    console.log(applyList)
    that.setData({
      applyList: applyList
    })
  },
  bindCode: function (e) {
    const that = this
    const applyList = that.data.applyList
    const id = e.currentTarget.dataset.id
    const codeValue = e.detail.value
    for (let i = 0; i < applyList.length; i++) {
      if (id == applyList[i].id) {
        applyList[i].storage_materiel_number = codeValue
      }
    }
    console.log(applyList)
    that.setData({
      applyList: applyList
    })
  },
  onAddPay: function () {
    const status = 'new'
    wx.navigateTo({
      url: "../storageAddPay/storageAddPay?status=" + status
    })
  },
  onSubmit: function (e) {
    const that = this
    const { list, message, payInfoList,sort_point } = this.data
    // const storage_net_weight =  app.globalData.storage_net_weight 
    const transferStorageList = app.globalData.transferStorageList
    console.log(transferStorageList)
    let applyList = that.data.applyList
    console.log(applyList)
    
    function isNumber(obj){
      return obj === +obj
    }
    let storage_materiel_number 
    let storage_amount_isNaN

    applyList && applyList.map( item => {
      storage_materiel_number = item.storage_materiel_number
      if (item.storage_amount == null){
        item.storage_amount = 0
       
      }
      if (item.pick_materiel_number == null){
        item.pick_materiel_number = ' '
      }
      if (  item.storage_materiel_number == null ){
        item.storage_materiel_number = ' '
      } else if (isNumber(item.storage_amount)  == false){
        storage_amount_isNaN = false 
     }
    })
    console.log(storage_amount_isNaN)
    console.log(isNumber(storage_amount_isNaN))
    let storage_net_weight
    let cargo_info = []
    transferStorageList && transferStorageList.map( item => {
      console.log(item)
      storage_net_weight = item.storage_net_weight
      cargo_info.push({
        "id":item.id,
        'storage_net_weight': item.storage_net_weight
      })
    })
    console.log(cargo_info)
    const data = {
      id: this.options.id,
      materiel_info: applyList,
      storage_remark: message,
      cargo_info: cargo_info,
      is_draft: 0,
      expense_info: payInfoList,
      sort_point: sort_point
    }
    console.log(data)
    
    if (storage_net_weight == null) {
      wx.showToast({
        title: '请填写货品入库净重',
        icon: 'none',
        duration: 1000
      })
    } else if (!sort_point){
      wx.showToast({
        title: '请选择分拣点',
        icon: 'none',
        duration: 1000
      })
    } else if (storage_amount_isNaN == false){
      wx.showToast({
        title: '请正确填写',
        icon: 'none',
        duration: 1000
      })
    }else{
      wx.showModal({
        title: '提示',
        content: '是否确认提交',
        success: function (res) {
          if (res.confirm){
            create({
              url: 'api/waste/purchase/storage_connect',
              params: { ...data },
              back: function (data) {
                if (data.code === 200) {
                  wx.navigateTo({
                    url: "../transferSuccess/transferSuccess?id="+that.options.id
                  })
                  console.log(111)
                }else {
                  
                }

              }
            })
          }else{
            console.log('用户点击取消')
          }
        }
      })
    }
  }
})